package com.gj.springbootrabbitmq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MyCallBack implements RabbitTemplate.ConfirmCallback ,RabbitTemplate.ReturnCallback{
    //ConfirmCallback是RabbitTemplate的内部接口
    /**
     * 发消息成功，交换机收到消息
     * ack=true
     * cause null
     *
     * 发消息失败，交换机收到消息
     * ack=false
     * cause 失败的原因
     * correlationData是id信息
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause)
    {
        String id=correlationData!=null?correlationData.getId():"";
        if(ack){
            log.info(" 交换机已经收到 id 为 :{} 的消息 ",id);
        }else{
            log.info(" 交换机还未收到 id 为 :{} 消息 , 由于原因 :{}",id,cause);
        }
    }

    // 当消息无法路由的时候的回调方法
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String
            exchange, String routingKey) {
        log.error(" message {}, return by {} exange ， because :{}, routing key:{}",new String(message.getBody()),exchange,replyText,routingKey);
    }
}
